﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using BZV.Foundation;
using BZV.Foundation.Business;
using System.Threading;
using BZV.Core.Net;

namespace LotteryHelper
{
    public partial class ListLotteryControl : UserControl, IDisposable
    {
        // 获取彩票的模块
        private LotteryQueryControl m_QueryControl;
        private QueryCode m_QueryCode;
        private string m_strID;
        private int m_nIssueCount = 0;
        private System.Timers.Timer m_TickTimer = new System.Timers.Timer();

        // 发送消息
        public DataPool m_DataPool;
        private LotteryComPerdictor m_Perdictor;

        public ListLotteryControl()
        {
            // 初始化界面
            InitializeComponent();

            // 初始化定时器
            m_TickTimer.Interval = 1000;
            m_TickTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timers_Timer_Elapsed);
        }

        public void Dispose()
        {
            m_DataPool.Save(m_strID + ".txt");
            m_TickTimer.Enabled = false;
        }

        public void SendMessage(string strTitle, string strBody)
        {
            string from = "woogle@sohu.com";
            string fromer = "发件人";
            string to = "406518296@qq.com";
            string toer = "收件人";
            string Subject = strTitle;
            string file = "";
            string Body = strBody;
            string SMTPHost = "smtp.sohu.com";
            string SMTPuser = "woogle@sohu.com";
            string SMTPpass = "31799800";

            new Thread((ThreadStart)delegate
                {
                    bool bOK = false;
                    // 失败最大为10次
                    for (int i = 0; i < 10; i++)
                    {
                        try
                        {
                            bOK = NetHelper.sendmail(from, fromer, to, toer, Subject, Body, file, SMTPHost, SMTPuser, SMTPpass);
                            if (bOK)
                            {
                                break;
                            }
                        }
                        catch (System.Exception ex)
                        {
                            continue;
                        }
                    }

                    // 发送失败
                    if (!bOK)
                    {
                        MessageBox.Show("发送失败！");
                    }
                    
                    
                }
                ).Start();

            
        }

        /// <summary>
        /// 初始化变量和自定义控件
        /// </summary>
        /// <param name="strID"></param>
        public void InitializeUI(string strID, int nIssueCount)
        {
            // 初始化变量
            m_QueryControl = new LotteryQueryControl(strID);
            m_strID = strID;
            m_nIssueCount = nIssueCount;

            // 更新数据
            m_DataPool = new DataPool(m_strID, m_nIssueCount);

            m_QueryCode = m_QueryControl.m_code;
            m_QueryControl.Load();

            // 添加事件
            this.Controls.Add(m_QueryControl);
            m_QueryControl.OnOpenHandler += new EventHandler(OnOpen);
            m_QueryControl.OnIntoWaiteHandler += new EventHandler(OnIntoWait);
            m_QueryControl.OnIntoCountDownHandler += new EventHandler(OnCountDown);
            m_QueryControl.OnIntoGetTimeHandler += new EventHandler(OnGetTme);

            m_Perdictor = new LotteryComPerdictor();
            m_Perdictor.SetData(m_DataPool.Lotterys);

            // 初始化常规
            m_grpBox.Text = this.Name;
            m_grpBox.Text = this.Name;

            // 初始化列表
            m_ListLottery.Columns.Add("期号", 90);
            m_ListLottery.Columns.Add("开奖号", 80);
            m_ListLottery.Columns.Add("组态");
            m_ListLottery.View = View.Details;


            // 初始化时间和彩票期号
            Lottery newLottery = m_DataPool.Lotterys[0];
            m_labCode.ForeColor = Color.YellowGreen;
            m_labCode.Font = new System.Drawing.Font("黑体", 12, FontStyle.Bold);
            SetBoundText(newLottery);

            // 离线的时候不查询
            bool bOnLine = NetHelper.CheckOnLine();
            if (bOnLine)
            {
                m_TickTimer.Start();
            }
            

            // 开始获取列表
            new Thread((ThreadStart)delegate
            {

                try
                {
                    this.Invoke((EventHandler)delegate
                    {
                        // 更新列表
                        if (m_DataPool.Lotterys != null)
                        {
                            UpdateList(m_DataPool.Lotterys);
                        }
                    });
                }
                catch (System.Exception ex)
                {

                }

               

            }
             ).Start();      

        }

        /// <summary>
        /// 更新彩票集合
        /// </summary>
        /// <param name="lotterys"></param>
        private void UpdateList(List<Lottery> lotterys)
        {
            // 清除以前的
            m_ListLottery.Items.Clear();
            int i = 0;
            foreach (Lottery lottery in lotterys)
            {
                if (i == 10)
                {
                    return;
                }

                i++;
                // 创建一行
                ListViewItem item = new ListViewItem();

                // 添加期号
                item.Text = lottery.Issue;

                // 添加开奖号
                ListViewItem.ListViewSubItem  subItem = item.SubItems.Add(lottery.Code);

                // 添加组态
                string strComState = "";
                ListViewItem.ListViewSubItem subItemCom = item.SubItems.Add("");
                switch (lottery.Param.comState)
                {
                    case CombinationState.EN_COM_ALL:           // 豹子 
                        {
                            strComState = "豹子";
                            subItemCom.BackColor = Color.Blue;
                            break;
                        }
                    case CombinationState.EN_COM_SIX:
                        {
                            strComState = "组六";
                            break;
                        }
                    case CombinationState.EN_COM_THREE:
                        {
                            strComState = "组三";
                            subItemCom.BackColor = Color.Red;
                            break;
                        }
                }
                subItemCom.Text = strComState;
                item.BackColor = subItemCom.BackColor;

                // 加入到列表中
                m_ListLottery.Items.Add(item);
            }
            
            
        }

        
        /// <summary>
        /// 设置开奖的实时信息
        /// </summary>
        /// <param name="lottery"></param>
        private void SetBoundText(Lottery lottery)
        {
            // 设置当前的颜色
            m_labTitle.Text = "第"
                + lottery.Issue.Substring(lottery.Issue.Length - 3, 3)
                + "期开奖号";
            m_labCode.Text = lottery.Code[0].ToString() + " "
                + lottery.Code[1].ToString() + " "
                + lottery.Code[2].ToString() + " "
                + lottery.Code[3].ToString() + " "
                + lottery.Code[4].ToString() + " "
                ;

            // 设置时间
            // 离线的时候不查询
            bool bOnLine = NetHelper.CheckOnLine();
            string strTime = "**";
            if (bOnLine)
            {
                strTime = m_QueryCode.startTime.strIssue.Substring(m_QueryCode.startTime.strIssue.Length - 3, 3);
            }

            m_labTime.Text = "距离"
                + strTime
                + "期时间:";
        }

        /// <summary>
        /// 节拍器触发方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Timers_Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            this.Invoke((EventHandler)delegate
            {
                // 获取时间差
                TimeSpan span = m_QueryCode.startTime.EndTime.AddSeconds(45) - DateTime.Now;

                // 显示
                if (span.Hours <= 0)
                {
                    m_labNextTime.Text = span.Minutes.ToString("00")
                    + "分" + span.Seconds.ToString("00") + "秒";
                }
                else
                {
                    m_labNextTime.Text = span.Hours.ToString("00") + "时" + span.Minutes.ToString("00")
                    + "分" + span.Seconds.ToString("00") + "秒";
                }
                
            }
             );
        } 

#region 开奖触发的事件
        /// <summary>
        /// 开奖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnOpen(object sender, EventArgs e)
        {
            // 更新彩票信息
            Lottery lo = (Lottery)sender;
            SetBoundText(lo);

            // 更新列表
            if (m_DataPool.Lotterys[0].Issue != lo.Issue)
            {
                m_DataPool.Lotterys.Insert(0, lo);
                m_DataPool.Lotterys.RemoveAt(m_DataPool.Lotterys.Count - 1);
                UpdateList(m_DataPool.Lotterys);
                m_DataPool.Lotterys.Add(lo);

                // 预测
                string strBody = "";
                UintParam forcast = m_Perdictor.ForecastRange(5, 10);
                strBody += "            未来5个走势为：\n";
                strBody += "组六个数：" + forcast.CombinationCount[CombinationState.EN_COM_SIX] + "\n";
                strBody += "组三个数：" + forcast.CombinationCount[CombinationState.EN_COM_THREE] + "\n";
                strBody += "豹子个数：" + forcast.CombinationCount[CombinationState.EN_COM_ALL] + "\n";


                // 发送消息
                string strTitle = lo.Issue + "期 ";
                
                
                
                if (m_nIssueCount == 120)
                {
                    strTitle += "旧时时彩";
                }
                else
                {
                    strTitle += "新时时彩";
                }
                strTitle += "：" + lo.Code.Substring(2, 3);
                SendMessage(strTitle, strBody);
            }

        }

        /// <summary>
        /// 进入等待开奖
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnIntoWait(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 倒计时
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnCountDown(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// 获取彩票
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnGetTme(object sender, EventArgs e)
        {
        }

#endregion
    }
}
